package org.elasticsearch.action.support;

import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;

public abstract class ToXContentToBytes implements ToXContent {

    private final XContentType defaultType;

    protected ToXContentToBytes() {
        this.defaultType = XContentType.JSON;
    }

    protected ToXContentToBytes(XContentType defaultType) {
        this.defaultType = defaultType;
    }


    public final BytesReference buildAsBytes() {
        return buildAsBytes(defaultType);
    }


    public final BytesReference buildAsBytes(XContentType contentType) {
        try {
            XContentBuilder builder = XContentFactory.contentBuilder(contentType);
            toXContent(builder, ToXContent.EMPTY_PARAMS);
            return builder.bytes();
        } catch (Exception e) {
            throw new RuntimeException("Failed to build ToXContent", e);
        }
    }

    @Override
    public final String toString() {
        return toString(EMPTY_PARAMS);
    }

    public final String toString(ToXContent.Params params) {
        try {
            XContentBuilder builder = XContentFactory.jsonBuilder();
            if (params.paramAsBoolean("pretty", true)) {
                builder.prettyPrint();
            }
            toXContent(builder, params);
            return builder.string();
        } catch (Exception e) {
            // So we have a stack trace logged somewhere
            return "{ \"error\" : \"" + e.getMessage() + "\"}";
        }
    }
}

